import socket
import json
import sys
import os


class ServiceController:
    def __init__(self, host='localhost', port=5899):
        self.host = host
        self.port = port

    def send_command(self, command):
        """发送命令到后台服务"""
        try:
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client_socket.settimeout(5)  # 5秒超时
            client_socket.connect((self.host, self.port))

            client_socket.send(command.encode('utf-8'))
            response = client_socket.recv(4096).decode('utf-8')

            client_socket.close()
            return response

        except ConnectionRefusedError:
            return "错误: 无法连接到后台服务，可能服务未运行"
        except socket.timeout:
            return "错误: 连接超时"
        except Exception as e:
            return f"错误: {e}"

    def display_status(self):
        """显示服务状态"""
        response = self.send_command("status")

        try:
            status = json.loads(response)
            print("=== 后台服务状态 ===")
            print(f"服务运行: {'是' if status['service_running'] else '否'}")
            print(f"监控应用: {status['monitored_apps']} 个")
            print(f"运行应用: {len(status['running_apps'])} 个")
            if status['running_apps']:
                print("运行中的应用:")
                for app in status['running_apps']:
                    print(f"  - {app}")
            else:
                print("运行中的应用: 无")
            print(f"日志文件: {status['log_file']}")
        except:
            print(f"状态响应: {response}")

    def stop_service(self):
        """停止服务"""
        print("正在停止后台服务...")
        response = self.send_command("stop")
        print(f"响应: {response}")

    def show_help(self):
        """显示帮助信息"""
        print("""
后台服务控制器 - 使用说明:

命令:
  status   - 查看服务状态
  stop     - 停止后台服务
  restart  - 重启服务(待实现)
  help     - 显示此帮助信息
  exit     - 退出控制器

示例:
  python service_controller.py status
  python service_controller.py stop
        """)

    def interactive_mode(self):
        """交互式模式"""
        print("=== 后台服务控制器 ===")
        print("输入 'help' 查看可用命令")

        while True:
            try:
                command = input("\n控制器> ").strip().lower()

                if command == 'exit' or command == 'quit':
                    break
                elif command == 'status':
                    self.display_status()
                elif command == 'stop':
                    self.stop_service()
                    break
                elif command == 'help':
                    self.show_help()
                elif command == 'restart':
                    response = self.send_command("restart")
                    print(f"响应: {response}")
                else:
                    print(f"未知命令: {command}")
                    print("输入 'help' 查看可用命令")

            except KeyboardInterrupt:
                print("\n退出控制器")
                break
            except EOFError:
                print("\n退出控制器")
                break


def main():
    controller = ServiceController()

    # 命令行参数处理
    if len(sys.argv) > 1:
        command = sys.argv[1].lower()

        if command == "status":
            controller.display_status()
        elif command == "stop":
            controller.stop_service()
        elif command == "restart":
            response = controller.send_command("restart")
            print(f"响应: {response}")
        elif command == "help":
            controller.show_help()
        else:
            print(f"未知命令: {command}")
            controller.show_help()
    else:
        # 交互式模式
        controller.interactive_mode()


if __name__ == "__main__":
    main()